package com.bawei.module_move.vm

import com.bawei.lib_common.vm.BaseViewModel
import com.bawei.module_move.repo.MoveRepository
import com.bawei.module_move.state.MoveStates
import com.example.movie.intent.MovieViewIntent
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class MoveViewModel @Inject constructor(private val apiserver:MoveRepository):BaseViewModel<MovieViewIntent>() {

    /**
     * 防止外部更改
     */
    //私有的防止外部修改StateFlow
    private val _uiStateFlow= MutableSharedFlow<MoveStates>()
    //对外暴露一个StateFlow用于收集数据变化
    val uiStateFlow: SharedFlow<MoveStates> = _uiStateFlow.asSharedFlow()

    override fun dispatchIntent(intent: MovieViewIntent) {
      when(intent){
          is MovieViewIntent.LoadLeverOneType->loadLeverOneType()
          is MovieViewIntent.LoadLeverTwoType->loadLeverTwoType(intent.pid)
      }
    }


    private fun loadLeverOneType(){
        mViewModelScope.launch  (mDispatcher){
            //发送请求
            apiserver.getMutilType().collect{list->
                if(list.isNotEmpty()){
                    _uiStateFlow.emit(MoveStates.LoadLeverOneTypeSuccess( list))
                }else{
                    _uiStateFlow.emit(MoveStates.LoadLeverOneTypeFail("没有请求成功分类数据"))
                }
            }
        }
    }

    private fun loadLeverTwoType(pid:Int){
        mViewModelScope.launch(mDispatcher){
            //发送请求
            apiserver.getMutilTypeByid(pid).collect{list->
                if(list.isNotEmpty()){
                    _uiStateFlow.emit(MoveStates.LoadLeverTwoTypeSuccess( list))
                }else{
                    _uiStateFlow.emit(MoveStates.LoadLeverTwoTypeFail("没有请求成功分类数据"))
                }
            }
        }
    }




}